package com.hb.shopping.controller;

import com.hb.shopping.pojo.ResultMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author hb
 * @create 2020-04-13 11:34
 */
@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public ResultMessage upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request)throws IOException {
        //获得文件名
        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);

        //根据逻辑路径获得绝对路径
        String path = request.getServletContext().getRealPath("file");
        //获得文件的绝对路径
        File filePath = new File(path, filename);

        //如果文件的上一级目录不存在则创建
        if(!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }
        //将文件写入目录中
        multipartFile.transferTo(filePath);

        return new ResultMessage(true,"/file/"+filename);

    }
}
